package com.syni.mdd.sjb.community.base.aop;

import com.syni.mdd.sjb.common.component.utils.common.annotations.CheckUserIdentity;
import com.syni.mdd.sjb.common.component.utils.common.constants.Constants;
import com.syni.mdd.sjb.common.component.utils.common.utils.RequestHeaderData;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.WebUtils;
import com.syni.mdd.sjb.community.base.constants.ResultCode;
import com.syni.mdd.sjb.community.base.constants.ResultMsg;
import com.syni.mdd.sjb.community.base.entity.vo.BaseRqVo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @className CheckParamsAspect
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/25 17:23
 * @VERSION 1.0
 **/
@Aspect
@Order(2)
@Component
public class ControllerCheckUserIdentify {
    private final Logger log = LoggerFactory.getLogger(getClass());

    private static String TOKEN_CHECK = Constants.TOKEN_CHECK;

    @Around("@annotation(checkUserIdentity)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint,  CheckUserIdentity checkUserIdentity) throws Throwable {
        Map<String,Object> argsMap = new HashMap<>();
        Object[] args = proceedingJoinPoint.getArgs();
        BaseRqVo baseRqVo = null;
        if(args.length > 0){
            for(Object arg : args){
                if(arg instanceof BaseRqVo){
                    baseRqVo = (BaseRqVo) arg;
                }
            }
        }
        if(baseRqVo != null){
            RequestHeaderData requestHeaderData = new RequestHeaderData();
            String token = requestHeaderData.getString("token");
            if(StringUtils.isBlank(token)){
                return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL, ResultMsg.MSG_TOKEN_FAIL);
            }
            String USER_TOKEN_CHECK = requestHeaderData.getString("user_token_check");
            String CHECK = WebUtils.MD5(token + TOKEN_CHECK);
            if(!CHECK.equals(USER_TOKEN_CHECK)) {
                return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL, ResultMsg.MSG_TOKEN_FAIL);
            }
            Integer userId = requestHeaderData.getInteger("userid");
            if(userId == null){
                return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL, ResultMsg.MSG_TOKEN_FAIL);
            }
            Integer client = requestHeaderData.getInteger("client");
            baseRqVo.setUserId(userId);
            baseRqVo.setToken(token);
            baseRqVo.setClient(client);
        }
        return proceedingJoinPoint.proceed(args);
    }
}
